import 'package:chatgreat/helper/platform.dart';
import 'package:chatgreat/repo/api/payment.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:bloc/bloc.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:meta/meta.dart';

part 'payment_event.dart';
part 'payment_state.dart';

class PaymentBloc extends Bloc<PaymentEvent, PaymentState> {
  PaymentBloc() : super(PaymentInitial()) {


    on<PaymentLoadAppleProducts>((event, emit) async {
      if (PlatformTool.isIOS()) {
        final products = await APIServer().paymentProducts();
        products.note = '所有订阅都会自动续订，直到您在付费期结束前至少24小时取消订阅为止。账户将在当期结束前的24小时内收取继续订阅的费用，并显示续订的金额。购买订阅后，您可以对其进行管理并在iTunes账户的设置中关闭自动续订。';
        if (products.data.isEmpty) {
          emit(PaymentAppleProductsLoaded(
            const <ProductDetails>[],
            note: products.note,
            error: '没有任何可购买的项目',
            localProducts: const [],
            loading: false,
          ));
          return;
        }

        print('===================> 111');
        emit(PaymentAppleProductsLoaded(
            products.data
                .map(
                  (e) => ProductDetails(
                    id: (e.appleId ?? 0).toString(),
                    title: e.name ?? '',
                    description: '',
                    price: '-',
                    rawPrice: 0,
                    currencyCode: '',
                  ),
                )
                .toList(),
            note: products.note,
            localProducts: products.data,
            loading: true));
        print('===================> 222');
        final productIds = products.data.map((e) => (e.appleId ?? '')).toSet();
        final response =
            await InAppPurchase.instance.queryProductDetails(productIds);
        if (response.notFoundIDs.isNotEmpty) {
          emit(PaymentAppleProductsLoaded(
            const <ProductDetails>[],
            note: products.note,
            localProducts: products.data,
            error: '没有任何可购买的项目',
            loading: false,
          ));
          return;
        }
        print('===================> 333');
        final remoteProducts = <ProductDetails>[];
        for (var id in productIds) {
          remoteProducts.add(
            response.productDetails.firstWhere((element) => element.id == id),
          );
        }

        emit(PaymentAppleProductsLoaded(
          remoteProducts,
          note: products.note,
          localProducts: products.data,
          loading: false,
        ));
        print('===================> 444');
      } else {
        final products = await APIServer().paymentProducts();
        if (products.data.isEmpty) {
          emit(PaymentAppleProductsLoaded(
            const <ProductDetails>[],
            note: products.note,
            error: '没有任何可购买的项目',
            localProducts: const [],
            loading: false,
          ));
          return;
        }

        emit(
          PaymentAppleProductsLoaded(
            products.data
                .map(
                  (e) => ProductDetails(
                    id: (e.id ?? 0).toString(),
                    title: e.name ?? '',
                    description: '',
                    price: '${e.price}',
                    rawPrice: e.orgPrice ?? 0.0,
                    currencyCode: '',
                  ),
                )
                .toList(),
            note: products.note,
            localProducts: products.data,
            loading: false,
            preferUSD: products.preferUSD,
          ),
        );
      }
    });

    on<PaymentLoadIntegralProducts>((event, emit) async {

        final products = await APIServer().integralProducts();
        products.note = '非订阅，以上套餐内容均为一次性购买';
        if (products.data.isEmpty) {
          emit(PaymentAppleProductsLoaded(
            const <ProductDetails>[],
            note: products.note,
            error: '没有任何可购买的项目',
            localProducts: const [],
            loading: false,
          ));
          return;
        }

        emit(PaymentAppleProductsLoaded(
            products.data
                .map(
                  (e) => ProductDetails(
                id: (e.appleId ?? 0).toString(),
                title: e.name ?? '',
                description: '',
                price: '-',
                rawPrice: 0,
                currencyCode: '',
              ),
            )
                .toList(),
            note: products.note,
            localProducts: products.data,
            loading: true));
        print('===================> 222');
        final productIds = products.data.map((e) => (e.appleId ?? '')).toSet();
        final response =
        await InAppPurchase.instance.queryProductDetails(productIds);
        if (response.notFoundIDs.isNotEmpty) {
          emit(PaymentAppleProductsLoaded(
            const <ProductDetails>[],
            note: products.note,
            localProducts: products.data,
            error: '没有任何可购买的项目',
            loading: false,
          ));
          return;
        }
        print('===================> 333');
        final remoteProducts = <ProductDetails>[];
        for (var id in productIds) {
          remoteProducts.add(
            response.productDetails.firstWhere((element) => element.id == id),
          );
        }

        emit(PaymentAppleProductsLoaded(
          remoteProducts,
          note: products.note,
          localProducts: products.data,
          loading: false,
        ));
        print('===================> 444');
    });

  }
}
